#include "RenderWidget.h"
#include "Scene/Scene.h"
#include <qgl.h>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QWheelEvent>
#include<QTimer>
namespace GCL {
RenderWidget::RenderWidget(Scene* scene, QWidget *parent)
    :scene_(scene), QGLWidget(parent)
{

    this->startTimer(scene_->interval());
    QTimer *timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(cubeRefresh()));
    timer->start(30);

}

RenderWidget::~RenderWidget()
{

}

void RenderWidget::cubeRefresh()
{
    scene_->cubeRotato();
    updateGL();
}

void RenderWidget::initializeGL()
{
    scene_->init();
}

void RenderWidget::resizeGL(int w, int h)
{
    scene_->resize(w,h);
    updateGL();
}

void RenderWidget::paintGL()
{
    scene_->render();

}

void RenderWidget::mousePressEvent(QMouseEvent *e)
{

    /// Screened Corrdinate System in OpenGL  start from left-bottom, is diffrent with  Qt's,
    /// Turn it into OpenGL screen corrdiantes;
    scene_->mousePress(e->x(),height() - e->y(),e->button(),e->modifiers());
    updateGL();
}

void RenderWidget::mouseReleaseEvent(QMouseEvent *e)
{
    scene_->mouseRelease(e->x(),height() - e->y(),e->button(),e->modifiers());
    updateGL();
}

void RenderWidget::mouseMoveEvent(QMouseEvent *e)
{
    scene_->mouseMove(e->x(),height() - e->y());
    updateGL();
}

void RenderWidget::wheelEvent(QWheelEvent *e)
{
    scene_->wheel((double)e->delta());
    updateGL();
}

void RenderWidget::timerEvent(QTimerEvent *)
{
    scene_->timerRun();
    updateGL();
}

void RenderWidget::keyReleaseEvent(QKeyEvent *e)
{
    scene_->keyUp(e->key(),e->modifiers());
}

}

